<script setup lang="ts">
import { getSimpleHotSearch, searchSong } from "@/api/content";
import Search from "@/components/Search/index.vue";
import { computed, onMounted, ref } from "vue-demi";
import HotSearchKeywords from "./components/HotSearchKeywords.vue";
import SearchKeywords from "./components/SearchKeywords.vue";
import SearchMatch from "./components/SearchMatch.vue";
import { debounce, uniq } from "@/utils/util";
import { useSearchStore } from "@/store/modules/search";

export interface ListProp {
  first: string;
  second: number;
}

const keyword = ref("");
// 热门搜索
const hotSearchList = ref<any[]>([]);
// 普通搜索
const searchList = ref<any[]>([]);
// 显示匹配
const showMatch = ref(false);

const store = useSearchStore();

// 输入框为空
const isEmptyKeyword = computed(() => keyword.value.trim().length === 0);

const hisList = computed(() => store.getSearchHistory);

onMounted(async () => {
  const { result } = await getSimpleHotSearch();
  hotSearchList.value = result.hots;
});

// 搜索
async function getSeachSong() {
  const res = await searchSong(keyword.value);
  searchList.value = res.result.allMatch.map((t: any) => ({
    first: t.keyword,
    second: t.type,
  }));
}

// 输入搜索
const handleChange = debounce(async () => {
  if (!isEmptyKeyword.value && !showMatch.value) {
    await getSeachSong();
  }
});

// 输入框聚焦
const handleFocus = async () => {
  if (isEmptyKeyword.value) return;
  showMatch.value = false;
  await getSeachSong();
};

// 清除
const handleClear = async () => {
  showMatch.value = false;
};

// 存储搜索记录
const setHotSeachHistory = ({
  first,
  second,
}: {
  first: string;
  second: number;
}) => {
  const list = [{ first, second }].concat(hisList.value);
  store.setSearchHistory(uniq(list, "first"));
};

// 点击名称搜索
const handleClickSearch = (item: ListProp) => {
  setHotSeachHistory({ first: item.first, second: item.second });
  keyword.value = item.first;
  showMatch.value = true;
};
</script>

<template>
  <div>
    <div class="px-2.5 py-4 border-b">
      <Search
        v-model="keyword"
        @change="handleChange"
        @focus="handleFocus"
        @clear="handleClear"
      ></Search>
    </div>
    <template v-if="!showMatch">
      <HotSearchKeywords
        v-if="isEmptyKeyword"
        :list="hotSearchList"
        @search="handleClickSearch"
      ></HotSearchKeywords>
      <SearchKeywords
        v-else
        :keyword="keyword"
        :list="searchList"
        @search="handleClickSearch"
      ></SearchKeywords>
    </template>
    <SearchMatch v-if="showMatch" :keyword="keyword"></SearchMatch>
  </div>
</template>

<style lang="scss" scoped></style>
